// 创建WelcomeActivity.kt
package com.a1573595.musicplayer.Welcome

import android.Manifest
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Address
import android.location.Criteria
import android.location.Geocoder
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.Settings
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.a1573595.musicplayer.R
import com.a1573595.musicplayer.songList.SongListActivity
import java.util.Locale
import com.a1573595.musicplayer.dbHelper.CityDatabaseHelper
import com.a1573595.musicplayer.dbHelper.DatabaseInitializer
import com.a1573595.musicplayer.weather.Weather
import com.android.volley.RequestQueue
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class WelcomeActivity : AppCompatActivity() {
    //这是一个明文访问 不太安全 需要在清单文件里加权限
    val baseUrl="http://t.weather.itboy.net/api/weather/city/"      //基础url
    private lateinit var cityCode: String//城市请求
    private lateinit var queue: RequestQueue // Volley请求队列
    private val LOCATION_PERMISSION_REQUEST_CODE = 1001//权限请求码
    private lateinit var result: List<Address>//地址信息
    private lateinit var mLocation: TextView//显示地址信息
    private val WHAT_LOCATE = 3//消息标识
    private lateinit var cityDatabaseHelper: CityDatabaseHelper // 数据库 Helper
    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == WHAT_LOCATE) {
                val location_city= result[0].locality//locality是地址信息中的城市
                val location = result[0].subLocality//0指的是第一个对象 不能改变  subLocality是地址信息中的区
                Log.e("Cityee", "当前定位的城市: $location")
                mLocation.text = "当前定位的城市: $location"

                // 在数据库中查找城市信息
                val city = cityDatabaseHelper.findCityByName(location)//city是一个City对象
                if (city != null) {
                    mLocation.text = "当前定位的城市: ${city.cityName} (ID: ${city.cityCode})"//返回对象的城市名与ID
                    cityCode = city.cityCode.toString()
                    fetchWeatherData() // 查询天气数据
                } else {
                    mLocation.text = "当前定位的城市: $location (未找到匹配数据)"
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_welcome111)
        mLocation = findViewById(R.id.tv_location)
        // 初始化数据库

        // 初始化请求队列
        queue = Volley.newRequestQueue(this)
        // 检查数据库是否已经初始化
        if (!isDatabaseInitialized()) {// 未初始化

            cityDatabaseHelper = CityDatabaseHelper(this)
            DatabaseInitializer(this).initialize()
            setDatabaseInitialized()

        } else {
            cityDatabaseHelper = CityDatabaseHelper(this)
        }

        checkLocationPermission()//权限的申请判断



    }
    private fun checkLocationPermission() {// 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {// 未授予权限
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), LOCATION_PERMISSION_REQUEST_CODE)// 申请权限
        } else {// 已授予权限
            location()  //展示
            loading()   // 延迟展示
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {// 处理权限请求结果
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {// 判断请求码
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {// 判断是否授予权限
                location()//权限授予，执行相关操作
                // 权限授予，执行相关操作
                loading()
            } else {// 权限拒绝，处理相关逻辑
                // 显示弹窗提示用户
                if_refuse()//权限被拒绝的处理
            }
        }
    }
    private  fun loading(){
        //延迟展示
        Handler(Looper.getMainLooper()).postDelayed({
            val intent = Intent(this, SongListActivity::class.java)
            startActivity(intent)
            finish()
        }, 5000) // 5秒
    }
    private  fun if_refuse(){
        // 显示弹窗提示用户
        AlertDialog.Builder(this)
            .setTitle("权限被拒绝")
            .setMessage("   该功能需要定位权限，您已拒绝权限，请重新启用权限以继续使用。")
            .setNegativeButton("设置") { _, _ ->
                // 打开应用设置
                val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivity(intent)
            }
            .setPositiveButton("退出") { _, _ ->
                // 关闭页面
                finish()
            }
            .setCancelable(false)
            .show()
    }

    /**
     * 定位获取当前城市
     */
    private fun location() {
        val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val criteria = Criteria().apply {
            isAltitudeRequired = false
            isBearingRequired = false
            isCostAllowed = false
            powerRequirement = Criteria.POWER_LOW
            accuracy = Criteria.ACCURACY_COARSE
        }
        var providerName = ""
        val providerList = locationManager.getProviders(true)
        providerName = when {
            providerList.contains(LocationManager.NETWORK_PROVIDER) -> LocationManager.NETWORK_PROVIDER
            providerList.contains(LocationManager.GPS_PROVIDER) -> LocationManager.GPS_PROVIDER
            else -> {
                Toast.makeText(this, "provider 获取失败", Toast.LENGTH_SHORT).show()
                return
            }
        }
        // 权限复验
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "权限未授权，请先授权UHello定位权限", Toast.LENGTH_SHORT).show()
            return
        }
        val location = locationManager.getLastKnownLocation(providerName)
        if (location != null) {
            val longitude = location.longitude // 经度
            val latitude = location.latitude // 纬度
            Log.e("TAG", "longitude = $longitude")
            Log.e("TAG", "latitude = $latitude")

            Log.d("AddressInfo", "开始获取地址信息")
            // 因为这里 Geocoder对象的 getFromLocation 方法，源码说明中建议在工作线程执行 getFromLocation方法
            Thread {
                try {
                    val geocoder = Geocoder(this, Locale.getDefault())
                    result = geocoder.getFromLocation(latitude, longitude, 1)!!
                    // 打印每个 Address 对象的详细信息
                    for (address in result) {
                        Log.d("AddressInfo", "国家: ${address.countryName}")
                        Log.d("AddressInfo", "省份: ${address.adminArea}")
                        Log.d("AddressInfo", "城市: ${address.locality}")
                        Log.d("AddressInfo", "区: ${address.subLocality}")
                        Log.d("AddressInfo", "街道: ${address.thoroughfare}")
                        Log.d("AddressInfo", "门牌号: ${address.subThoroughfare}")
                        Log.d("AddressInfo", "邮政编码: ${address.postalCode}")
                        Log.d("AddressInfo", "纬度: ${address.latitude}")
                        Log.d("AddressInfo", "经度: ${address.longitude}")
                    }

                    mHandler.sendEmptyMessage(WHAT_LOCATE)

                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }.start()
        } else {
            Toast.makeText(this, "UHello 定位失败", Toast.LENGTH_SHORT).show()
        }
    }
    private fun isDatabaseInitialized(): Boolean {// 检查数据库是否已经初始化
        val sharedPreferences = getSharedPreferences("app_prefs", Context.MODE_PRIVATE)//获取SharedPreferences对象
        return sharedPreferences.getBoolean("database_initialized", false)
    }

    private fun setDatabaseInitialized() {// 设置数据库已经初始化
        val sharedPreferences = getSharedPreferences("app_prefs", Context.MODE_PRIVATE)
        with(sharedPreferences.edit()) {//使用 apply() 方法将数据保存到 SharedPreferences 中
            putBoolean("database_initialized", true)
            apply()
        }
    }

    private fun fetchWeatherData() {
        Log.d("post_1", "进入fetchWeatherData")
        Log.d("post_1", "base: ${baseUrl}")
        Log.d("post_1", "citycode: ${cityCode}")
        Log.d("post_1", "url: ${baseUrl + cityCode}")
        val stringRequest = StringRequest(baseUrl + cityCode, { response ->
            Log.d("post_1", "进入url: ${baseUrl + cityCode}")
            val gson = Gson()
            val weatherType = object : TypeToken<Weather>() {}.type
            val weather: Weather = gson.fromJson(response, weatherType)

            // 更新UI
            val caring = findViewById<TextView>(R.id.tv_caring)
            caring.text = weather.data.forecast[0].notice
            val cur_weather = findViewById<TextView>(R.id.tv_weather)
            cur_weather.text = weather.data.forecast[0].type



            val today = weather.data.forecast[0]
            when {
                //这里需要根据天气类型来设置图片
                today.type == "晴" -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
                today.type == "多云" -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
                today.type.contains("雨") -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
                today.type == "阴" -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
                today.type == "雪" -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
                today.type == "雷电" -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
                else -> findViewById<ImageView>(R.id.img_weather).setImageResource(R.drawable.pink_home)
            }
        }, { error ->
            Toast.makeText(this, "网络请求失败", Toast.LENGTH_SHORT).show()
            Log.d("post_1", "网络请求失败: ${error.message}")
        })
        queue.add(stringRequest)
    }


    override fun onDestroy() {
        super.onDestroy()
        cityDatabaseHelper.close()
    }


}
